package com.zhao.dota.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhao.dota.bo.AuthenticateUser;
import com.zhao.dota.security.SecurityUtil;
import com.zhao.dota.security.store.TokenStore;
import com.zhao.dota.struct.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LogoutHandler implements LogoutSuccessHandler {


    private final TokenStore tokenStore;

    private final ObjectMapper objectMapper;

    @Autowired
    public LogoutHandler(TokenStore tokenStore, ObjectMapper objectMapper) {
        this.tokenStore = tokenStore;
        this.objectMapper = objectMapper;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String authorization = request.getHeader("Authorization");
        tokenStore.removeAccessToken(authorization);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(Result.success()));
    }
}
